/**
 * 
 */
package com.game.jumpdino;

import com.game.jumpdino.logic.GameState;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * @author HugoGu
 *
 */
public class JumpingView extends SurfaceView implements SurfaceHolder.Callback {	
	private GameThread mThread;
	private static JumpingView current;
	
	/**
	 * @param context
	 * @param attrs
	 */
	public JumpingView(Context context, AttributeSet attrs) {
		super(context, attrs);
		current = this;
        // register our interest in hearing about changes to our surface
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
        mThread = new GameThread(holder, context);
        
        setFocusable(true); // make sure we get key events
	}
	
	public static JumpingView getCurrent(){
		return current;
	}
	
	public GameThread getThread(){
		return mThread;
		
	}
	
	@Override
	public boolean verifyDrawable(Drawable who){
		return who != null;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event){
		return mThread.doKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event){
		return mThread.doKeyUp(keyCode, event);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		mThread.getPlayground().initialPlaygroundSize(width, height);
		mThread.getPlayground().setState(GameState.Ready);
	}

	public void surfaceCreated(SurfaceHolder holder) {
		if (!mThread.isAlive()){
			mThread.start();
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// the Jumping view only destroy when application exit.
		try
		{
			mThread.join(500);
		} catch (InterruptedException ex){
			
		}
	}
}
